package cn.wolfcode.Controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeObject;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.qo.jsonResult;
import cn.wolfcode.service.DepartmentService;
import cn.wolfcode.service.EmployeeService;
import cn.wolfcode.service.impl.RoleServiceImpl;
import cn.wolfcode.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private RoleServiceImpl roleService;

    private DepartmentService departmentService;
    @Autowired
    public void setDepartmentService(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    private EmployeeService employeeService;
    @Autowired
    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }




//    @RequestMapping("/list")
//    public String listAll(Model model){
//        List<Employee> employees = employeeMapper.selectAll();
//        model.addAttribute("employees",employees);
//        return "employee/list";
//    }

    @RequirePermission(name = "查看员工",experssion = "employee:list")
    @RequestMapping("/list")
    public String listAll(Model model, @ModelAttribute("qo") EmployeeObject qo){
        PageInfo<Employee> pageInfo = employeeService.listPage(qo);
        model.addAttribute("pageInfo",pageInfo);
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        return "employee/list";
    }

    @RequirePermission(name = "删除员工",experssion = "employee:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null){
            employeeService.deleteByPrimaryKey(id);
        }
        return "redirect:/employee/list";
    }


//    @RequirePermission(name = "批量删除员工",experssion = "employee:deleteInBatches")
//    @RequestMapping("/deleteInBatches")
//    @ResponseBody
//    public jsonResult deleteInBatches(Long[] ids){
//        if (ids != null){
//            try {
//                employeeService.deleteInBatches(ids);
//            } catch (Exception e) {
//                return new jsonResult(false,"批量删除失败");
//            }
//        }
//        return new jsonResult();
//    }

    @RequirePermission(name = "员工新增/编辑",experssion = "employee:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles", roles);
        if (id != null){
            Employee employee = employeeService.selectByPrimaryKey(id);
            System.out.println(employee);
            model.addAttribute("employee", employee);
        }
        return "employee/input";
    }

//    @RequirePermission(name = "员工新增/编辑",experssion = "employee:saveOrUpdate")
//    @RequestMapping("/saveOrUpdate")
//    public String saveOrUpdate(Employee employee,Model model, Long[] ids){
//        System.out.println(employee);
//        if (employee.getId() != null){
//            employeeService.updateByPrimaryKey(employee);
//            //先删除之前的关联关系在进行重新关联插入
//            //这样不需要判断
//            //删除关系
//            roleService.deleteRelation(employee.getId());
//            //添加关系
////            roleService.insertRelation(employee.getId(), ids);
//        }else {
//            employeeService.insert(employee);
//            //由于是是添加,所以不需要删除关系,进行添加关系即可
////            roleService.insertRelation(employee.getId(), ids);
//        }
//        if (ids != null && ids.length>0){
//            roleService.insertRelation(employee.getId(), ids);
//        }
//
//        return "redirect:/employee/list";
//    }



    @RequirePermission(name = "员工新增/编辑",experssion = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public jsonResult saveOrUpdate(Employee employee,Model model, Long[] ids){
        if (employee.getId() != null){
            try {
                employeeService.updateByPrimaryKey(employee);
                //先删除之前的关联关系在进行重新关联插入
                //这样不需要判断
                //删除关系
                roleService.deleteRelation(employee.getId());
                if (ids != null && ids.length>0){
                    roleService.insertRelation(employee.getId(), ids);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new jsonResult(false,"修改失败");
            }
            //添加关系
//            roleService.insertRelation(employee.getId(), ids);
        }else {
            try {
                //由于是是添加,所以不需要删除关系,进行添加关系即可
//            roleService.insertRelation(employee.getId(), ids);
                employeeService.insert(employee);
                if (ids != null && ids.length>0){
                    roleService.insertRelation(employee.getId(), ids);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new jsonResult(false,"添加失败");
            }
        }


        System.out.println("sdd");

        return  new jsonResult(true,"操作成功");
    }


    @RequestMapping("/checkName")
    @ResponseBody
    public Map<String,Boolean> checkName(String username){
        Map<String, Boolean> map = new HashMap<>();
        Employee employee = employeeService.checkUsername(username);
        map.put("valid", employee==null);
        return map;

    }

    @RequestMapping("/exportXls")
    @RequirePermission(name = "文件导出",experssion = "employee:exportXls")
    @ResponseBody
    public void exportXls(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
       //创建excel文件
        Workbook workbook = new HSSFWorkbook();
        //创建sheet,表格
        Sheet sheet = workbook.createSheet();
        //创建标题行
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("密码");
        row.createCell(2).setCellValue("年龄");


        List<Employee> employees = employeeService.selectAll();
        for (int i = 0 ;i < employees.size(); i++){
            Employee employee = employees.get(i);
            //创建行对象
            Row row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(employee.getName());
            //因为setCellValue(x);
            //底层是相当于x.toString()方法，也就是将x转为字符串的方法
            //所以x的值不能为空，否则空指针异常
            row1.createCell(1).setCellValue(employee.getPassword());
            row1.createCell(2).setCellValue(employee.getAge());
        }
        workbook.write(response.getOutputStream());

    }


    //文件上传
    @RequestMapping("/importXls")
    @RequirePermission(name = "文件导入",experssion = "employee:importXls")
    @ResponseBody
    public jsonResult importXls(MultipartFile file)  {
        try {
            employeeService.importXls(file);
        } catch (IOException e) {
            return new jsonResult(false,"导入失败");
        }
        return  new jsonResult(true,"导入成功");

    }


    @RequestMapping("/updateStatus")
//    @RequirePermission(name = "文件导入",experssion = "employee:importXls")
    public String updateStatus(Long id,Long status)  {
        System.out.println(id+":"+status);
        if (status == 1){
            employeeService.updateStatus(0,id);
        }else {
            employeeService.updateStatus(1,id);
        }
      return "redirect:/employee/list";
    }

}

